//
//  GroupDetailVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/25.
//

import UIKit

class GroupDetailVC: BaseVC, GroupDetailHeadDelegate {
    
    lazy var memberList : [DMCCMember] = {
        let memberList = gosnMember.getMemberList(con.targetId, 0, 15)
        Task {
           let members = await gosnMember.updateMemberZone(con.targetId, 0, 15)
            await MainActor.run {
                if members.count != self.memberList.count && members.count > 0 {
                    self.memberList = members
                    self.tableView.reloadData()
                }
            }
 
        }
        //let memberList = DMCCIMService.getInstance().getGroupZoneMembersTopSilent(con.targetId, forceUpdate: true)
        return memberList
    }()
    var group = DMCCGroup()
    var con = DMCCConversation()
    lazy var myInfo : DMCCUser = {
//        let myInfo = gosnUser.getUserInfo(gosnUser.myId(), inGroup: self.con?.targetId, refresh: false)
//        return myInfo!
        return gosnUser.getUserInfoDefault("")
    }()
    
    init(group: DMCCGroup = DMCCGroup(),con: DMCCConversation = DMCCConversation()) {
        super.init(nibName: nil, bundle: nil)
        self.group = group
        self.con = con
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "群聊详情"
        setup()
    }


    func setup () {
//        dataSource = [["head","免打扰","置顶"],["查找聊天记录"],["推荐给好友","清空聊天记录"],["投诉"],["删除会话"]]
//        dataSource = [["群聊名称","我的本群的昵称","二维码","群公告","群管理"],["查找聊天记录"],["免打扰","置顶","保存到通讯录","显示群成员昵称"],["投诉"],["清空聊天记录"],["退出群聊"]]
        dataSource = [["群聊名称","我的本群的昵称","二维码"],["群公告","群管理"],["查找聊天记录"],["免打扰","置顶","保存到通讯录","显示群成员昵称"],["投诉"],["清空聊天记录"],["退出群聊"]]
        
        tableView.dataSource = self
        tableView.delegate = self
        tableStytle = .grouped
        
        tableView.register(GroupDetailHeadView.self, forHeaderFooterViewReuseIdentifier: "GroupDetailHeadView")
        tableView.register(GroupDetailHeadCell.self, forCellReuseIdentifier: "GroupDetailHeadCell")
//        tableView.register(UINib(nibName: "GroupDetailHeadCell", bundle: nil), forCellReuseIdentifier: "GroupDetailHeadCell")
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
        tableView.register(UINib(nibName: "SubTitleCell", bundle: nil), forCellReuseIdentifier: "SubTitleCell")
        tableView.register(UINib(nibName: "SwitchCell", bundle: nil), forCellReuseIdentifier: "SwitchCell")
        tableView.register(UINib(nibName: "LogoutCell", bundle: nil), forCellReuseIdentifier: "LogoutCell")
        tableView.reloadData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(onGroupRefreshChanged), name: NSNotification.Name(rawValue: kGroupUpdateChanged), object: nil)
        geventService.addObserver(OsnEvent.GroupInfoUpdated, "GroupInfoUpdated_GroupDetailVC") { [weak self] data in
            guard let self = self else {return}
            self.updateMember()
        }
        
    }
    
    @objc func onGroupRefreshChanged () {
        updateGroup()
    }
    
    func updateMember () {
        GK_main_async_safe {
            self.updateGroup()
            self.memberList = gosnMember.getMemberList(self.con.targetId, 0, 15)
            self.tableView.reloadData()
        }
    }
    
    func updateGroup () {
        let group = gosnGroup.getGroupInfoDefault(self.group.groupId)
        self.group = group
        GK_main_async_safe {
            self.tableView.reloadData()
        }
    }
    
    func updateMyInfo () {
        self.myInfo = gosnUser.getUserInfoDefault("")
    }
    
    func isGroupOwner() -> Bool {
        let owner = group.owner
        if owner.isEmpty {
            return false
        }
        return owner == gosnUser.myId()
    }
    
    func isGroupManger() -> Bool {
        if let gm = gosnMember.getMemberInfo(con.targetId, gosnUser.myId()),
           gm.type == OsnMemberType.Admin || gm.type == OsnMemberType.Owner {
            return true
        }
        return false
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if (indexPath.section == 0 && indexPath.row == 4) {
            return 0
        }
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array = dataSource[section] as! Array<String>
        return array.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            let memberCount = memberList.count
            let addNum = isGroupOwner() ? 2 : 1

            var num = (13 + addNum) / 5
            let remainder = (13 + addNum) % 5

            if remainder != 0 {
                num += 1
            }
            
            let height = 80 * num + 50 + 40

            if memberCount >= 15 {
                return CGFloat(height)
            } else {
                let numMembers = memberCount + addNum
                var num = numMembers / 5
                let remainder = numMembers % 5

                if remainder != 0 {
                    num += 1
                }

                return CGFloat(80 * num + 40)
            }
        }
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 0 {
            let head = tableView.dequeueReusableHeaderFooterView(withIdentifier: "GroupDetailHeadView") as! GroupDetailHeadView
            head.delegate = self
            var arr : [DMCCMember]
            if memberList.count >= 15 {
                if isGroupOwner() || isGroupManger() {
                    arr = Array(memberList[0..<13])
                } else {
                    arr = Array(memberList[0..<14])
                }
    //                isShow = true
                head.isMore = true
            } else {
                head.isMore = false
                arr = memberList
            }
            
            head.data = arr
            head.isManager = isGroupManger() || isGroupOwner()
            head.info = group
            head.update()
            return head
        }
        return UIView()
        
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 10))
        view.backgroundColor = UIColor.clear
        return view
    }
    
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 10))
//        view.backgroundColor = UIColor.lightGray
//        return view
//    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        [["head"],["群聊名称","我的本群的昵称","二维码","群公告","群管理"],["查找聊天记录"],["免打扰","置顶","保存到通讯录","显示群成员昵称"],["推荐给好友"],["投诉"],["清空聊天记录"],["退出群聊"]]
        let array = self.dataSource[indexPath.section] as! Array<String>
        let name = array[indexPath.row]
        
//        if indexPath.section == 0 {
//            let cell = GroupDetailHeadCell(style: .default, reuseIdentifier: "GroupDetailHeadCell")
//            cell.delegate = self
//            var arr : [MemberInfo]
//            if memberList.count > 25 {
//                if isGroupOwner() || isGroupManger() {
//                    arr = Array(memberList[0..<23])
//                } else {
//                    arr = Array(memberList[0..<24])
//                }
////                isShow = true
//                cell.isMore = true
//            } else {
//                cell.isMore = false
//                arr = memberList
//            }
//            
//            cell.data = arr
//            cell.isManager = isGroupManger() || isGroupOwner()
//            cell.info = group
//            cell.update()
//            return cell
//        }
        
        if (indexPath.section == 0 && indexPath.row == 0) ||  (indexPath.section == 0 && indexPath.row == 1) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SubTitleCell", for: indexPath) as! SubTitleCell
            cell.titleLab.text = name
            if indexPath.row == 0 {
                cell.subTitleLab.text = group.name
            }else{
                let member = gosnMember.getMemberInfoDefault(group.groupId, myInfo.userId)
                if member.alias.count > 0 {
                    cell.subTitleLab.text = member.alias
                }else{
                    cell.subTitleLab.text = myInfo.getAlias()
                }
                
            }
            return cell
        }
        
        if (indexPath.section == 0 && indexPath.row == 4)  {
            let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
            cell.contentView.backgroundColor = UIColor.clear
            cell.accessoryType = .none
            return cell
        }
        
        if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell", for: indexPath) as! SwitchCell
            cell.titleLab.text = name
            
            if indexPath.row == 0 {
                cell.type = .NoticeType
                cell.con = self.con
                cell.sw.setOn(self.con.isSilent, animated: false)
            }else if indexPath.row == 1{
                cell.type = .TopType
                cell.con = self.con
                cell.sw.setOn(self.con.isTop, animated: false)
            }else if indexPath.row == 2{ //保存通讯录
                cell.type = .SaveGroup
                cell.con = self.con
                cell.sw.setOn((group.fav), animated: false)
            }else if indexPath.row == 3{ //显示群昵称
                cell.type = .ShowName
                cell.con = self.con
                cell.sw.setOn((group.showAlias), animated: false)
            }
            
            return cell
        }
        
//        dataSource = [["head","免打扰","置顶"],["查找聊天记录"],["推荐给好友","清空聊天记录"],["投诉"],["删除会话"]]
        
        if  indexPath.section == 6{
            let cell = tableView.dequeueReusableCell(withIdentifier: "LogoutCell", for: indexPath) as! LogoutCell
             
            if isGroupOwner() {
                cell.titleLab.text = "解散并退出群聊"
            }else{
                cell.titleLab.text = "退出群聊"
            }
            
            cell.titleLab.textColor = UIColor.red
            return cell
        }
        
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.contentView.backgroundColor = UIColor.clear
        cell.accessoryType = .disclosureIndicator
        cell.textLabel?.text = name
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        
        if (indexPath.section == 0  && indexPath.row == 0) {//群名称
            changeGroupNameAlert()
        }else if (indexPath.section == 0  && indexPath.row == 1) {//本群昵称
            self.presentVC(VC: SetNickNameVC(type: .group, SId: group.groupId, dismissCompletion: { [self] in
                self.updateMyInfo()
                GK_main_async_safe {
                    self.tableView.reloadData()
                }
            }))

        }else if (indexPath.section == 0  && indexPath.row == 2) {//二维码
            //let con = ConversationInfo.init(param: con.targetId, type: 0)
            let con = gosnConversation.getConversationInfoDefault(con.targetId)
            navigationController?.pushViewController(QRVC(with: con, isGroup: true, isUser: false), animated: true)
        }else if (indexPath.section == 1  && indexPath.row == 0) {//群公告
            guard isGroupOwner() || isGroupManger() else {
                MHAlert.showMessage(KLocalizedString("AlertNoOurthSee"))
                return
            }
            self.presentVC(VC: NoticeVC(group: group))
        } else if (indexPath.section == 1  && indexPath.row == 1) {//群管理
            guard isGroupOwner() || isGroupManger() else {
                MHAlert.showMessage(KLocalizedString("AlertNoOurthSee"))
                return
            }
            navigationController?.pushViewController(GroupManagerVC(group: group), animated: true)
        } else if indexPath.section == 2 {
            navigationController?.pushViewController(ChatSearchVC.init(self.con), animated: true)
        }else if (indexPath.section == 4) {
            self.navigationController?.pushViewController(ReportVC(isGroup: false), animated:  true)
        } else if indexPath.section == 5 {
            let str = KLocalizedString("确定清空聊天记录吗")
            MHAlert.showCustomAlert(str) { ac in
                if ac.title == KLocalizedString("Sure") {
                    self.deleUserClick()
                }
            }
        } else if indexPath.section == 6{
            if isGroupOwner() {
                handleDeleteGroup()
            }else{
                handleQuitGroup()
            }
        }
    }
    
    func handleQuitGroup() {
        let str = KLocalizedString("AlertSureQuitGroup")
        
        MHAlert.showCustomAlert(str) { ac in
            if ac.title == KLocalizedString("Sure") {
                MHAlert.showLoading()

                Task {
                    let res = await gosnGroup.quitGroup(self.con.targetId)
                    if res {
                        _ = gosnConversation.deleteConversation(self.con.targetId)
                        _ = gosnGroup.delGroupInfo(self.con.targetId)
                    }
                    await MainActor.run {
                        if res {
                            MHAlert.showMessage(KLocalizedString("GroupMessageBeenSended"))
                            geventService.post(.kUpDateConversation, "")
                            self.navigationController?.popToRootViewController(animated: true)
                        }else{
                            MHAlert.showMessage(KLocalizedString("GroupMessageTimeOut"))
                        }
                    }
                }
            }
        }
        

    }
    
    func handleDeleteGroup() {
        let str = KLocalizedString("AlertSureDisDel")
        MHAlert.showCustomAlert(str) { ac in
            if ac.title == KLocalizedString("Sure") {
                MHAlert.showLoading()

                Task {
                    _ = await gosnGroup.saveGroup(self.con.targetId, false)
                    _ = gosnGroup.delGroupInfo(self.con.targetId)
                    let res = await gosnGroup.dismissGroup(self.con.targetId)
                    if res {
                        _ = gosnConversation.deleteConversation(self.con.targetId)
                        _ = gosnGroup.delGroupInfo(self.con.targetId)
                    }
                    await MainActor.run {
                        if res {
                            MHAlert.showMessage(KLocalizedString("GroupMessageBeenSended"))
                            geventService.post(.kUpDateConversation, "")
                            self.navigationController?.popToRootViewController(animated: true)
                        }else{
                            MHAlert.showMessage(KLocalizedString("GroupMessageTimeOut"))
                        }
                    }
                }
            }
        }
    }
    
    func changeGroupNameAlert() {
        guard isGroupOwner() else {
            MHAlert.showMessage(KLocalizedString("AlertNoOurthSee"))
            return
        }
        let title = "修改群名称"
        let topVC = UIApplication.shared.keyWindow?.rootViewController ?? UIViewController()
        let presentedVC = topVC.presentedViewController
        let vc = presentedVC ?? topVC

        let alert = UIAlertController(title: title, message: "", preferredStyle: .alert)
        let okAction = UIAlertAction(title: KLocalizedString("Sure"), style: .default) { [self] _ in
            guard let inputText = alert.textFields?.first?.text, inputText.count <= 12 else {
                MHAlert.showMessage(KLocalizedString("NickNameLengthToLong"))
                return
            }

            if let dic = UserDefaults.standard.object(forKey: MHHYCrossImSensitiveWords) as? [String: Any],
               let sensitiveWordsArr = dic["keywordArray"] as? [String],
               sensitiveWordsArr.contains(where: { inputText.localizedCaseInsensitiveContains($0) }) {
                MHAlert.showMessage(KLocalizedString("GroupNameViolatingRegulations"))
                return
            }

            MHAlert.showLoadingStr("")
            Task {
                _ = await gosnGroup.setGroupName(group.groupId, inputText)
                await MainActor.run {
//                    if res {
                        
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            MHAlert.showMessage(KLocalizedString("GroupChangeNameSuccess"))
                            self.group.name = inputText
                            self.tableView.reloadData()
                        }
//                    }else{
//                        MHAlert.showMessage(KLocalizedString("群名称修改失败"))
//                    }
                }
            }
        }

        let cancelAction = UIAlertAction(title: KLocalizedString("Cancel"), style: .default, handler: nil)

        alert.addTextField { [self] textField in
            textField.placeholder = KLocalizedString("ModifyGroupName")
            textField.text = group.name
            textField.clearButtonMode = .always
        }

        alert.addAction(cancelAction)
        alert.addAction(okAction)
        vc.present(alert, animated: true, completion: nil)
    }
    
    func deleUserClick() {
        _ = gosnMessage.clearMessage(con.targetId)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            MHAlert.showMessage("清空完成")
        }
    }

    
//    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        if scrollView == tableView {
//            let sectionHeaderHeight = CGFloat(45.0)//headerView的高度
//            if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
//                
//                scrollView.contentInset = UIEdgeInsets(top: -scrollView.contentOffset.y, left: 0, bottom: 0, right: 0);
//                
//            } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
//                
//                scrollView.contentInset = UIEdgeInsets(top: -sectionHeaderHeight, left: 0, bottom: 0, right: 0);
//            }
//        }
//    }

    
    // MARK: - Head Delegate
    func FriendAddBlock() {
        
        let vc = GroupAddUserVC(group: group)
        vc.confirmBlock = { [weak self] array in
            MHAlert.showLoading()
            Task {
                guard let strongSelf = self else { return }
                _ = await gosnGroup.addGroupMembers(strongSelf.con.targetId, array)
                await MainActor.run {
                    MHAlert.showMessage(KLocalizedString("GroupMessageBeenSended"))
                }
            }
        }
        
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func FriendLessBlock() {
        
        let vc = GroupLessUserVC(group: group)
        vc.confirmBlock = { [weak self] array in
            MHAlert.showLoading()
            Task {
                _ = await gosnGroup.delGroupMembers(self?.con.targetId ?? "", array)
                await MainActor.run {
                    MHAlert.showMessage(KLocalizedString("GroupMessageBeenSended"))
                }
            }
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func FriendSeeBlock(index: Int) {
        let member = memberList[index] 
        let userInfo = gosnUser.getUserInfoDefault(member.memberId)
        if userInfo.userId == gosnUser.myId() {
            self.navigationController?.pushViewController(MySetVC(), animated: true)
        }else if gosnFriend.isFriend(userInfo.userId) {
            let detailViewController = UserDetailVC(userInfo: userInfo)
            navigationController?.pushViewController(detailViewController, animated: true)
        } else {
            let addFriendViewController = AddUserVC(userInfo: userInfo)
            navigationController?.pushViewController(addFriendViewController, animated: true)
        }
        
    }
    
    func FriendSeeMoreBlock() {
        
        navigationController?.pushViewController(GroupMemberVC(group: group), animated: true)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kGroupUpdateChanged), object: nil)
        geventService.removeObserver(OsnEvent.GroupInfoUpdated, "GroupInfoUpdated_GroupDetailVC")
    }
}
